package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.constant.FieldTypeConstant;
import com.zb.entity.FieldValOptionVo;
import com.zb.entity.ZjWorkFieldVal;
import com.zb.entity.ZjWorkFieldValOption;
import com.zb.entity.ZjWorkModuleField;
import com.zb.extend.WorkFieldValExtend;
import com.zb.mapper.ZjWorkFieldValMapper;
import com.zb.service.ZjWorkFieldValOptionService;
import com.zb.service.ZjWorkFieldValService;
import com.zb.service.ZjWorkModuleFieldService;
import com.zb.vo.WorkDetailFieldParamVo;
import com.zb.vo.WorkFieldValVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 工单字段值表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-10-12
 */
@Service
public class ZjWorkFieldValServiceImpl extends ServiceImpl<ZjWorkFieldValMapper, ZjWorkFieldVal> implements ZjWorkFieldValService {
    @Resource
    private ZjWorkFieldValMapper workFieldValMapper;
    @Resource
    private ZjWorkModuleFieldService workModuleFieldService;
    @Resource
    private ZjWorkFieldValOptionService workFieldValOptionService;

    // 保存、修改工单自定义字段
    @Override
    public void save(Long custAccId, Long workId, List<WorkFieldValVo> workFieldVal) {
        if (null == workFieldVal || workFieldVal.isEmpty()) {
            return;
        }
        List<ZjWorkFieldVal> adds = new ArrayList<>();
        List<ZjWorkFieldVal> updates = new ArrayList<>();
        ZjWorkFieldVal fieldVal = null;
        List<ZjWorkFieldValOption> addValOpts = new ArrayList<>();
        List<ZjWorkFieldValOption> updateValOpts = new ArrayList<>();
        ZjWorkFieldValOption valOpt = null;
        for (WorkFieldValVo vo : workFieldVal) {
            fieldVal = new ZjWorkFieldVal();
            BeanUtil.copyProperties(vo, fieldVal);
            if (null != fieldVal.getId()) {
                updates.add(fieldVal);
            } else {
                fieldVal.setId(IdWorker.getId());
                fieldVal.setCustAccId(custAccId);
                fieldVal.setWorkId(workId);
                adds.add(fieldVal);
            }
            if (CollectionUtil.isNotEmpty(vo.getOptionVos())) {
                for (FieldValOptionVo optionVo : vo.getOptionVos()) {
                    valOpt = new ZjWorkFieldValOption();
                    BeanUtil.copyProperties(optionVo, valOpt);
                    valOpt.setOptValue(null == valOpt.getOptValue()? "" : valOpt.getOptValue());
                    if (null != valOpt.getId()) {
                        updateValOpts.add(valOpt);
                        continue;
                    }
                    valOpt.setId(IdWorker.getId());
                    valOpt.setCustAccId(custAccId);
                    valOpt.setWorkId(workId);
                    valOpt.setWorkFieldValId(fieldVal.getId());
                    addValOpts.add(valOpt);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(adds)) this.saveBatch(adds);
        if (CollectionUtil.isNotEmpty(updates)) this.updateBatchById(updates);
        if (CollectionUtil.isNotEmpty(addValOpts)) workFieldValOptionService.saveBatch(addValOpts);
        if (CollectionUtil.isNotEmpty(updateValOpts)) workFieldValOptionService.updateBatchById(updateValOpts);
    }

    // 根据工单模块字段ID查询关联的工单字段ID
    @Override
    public List<Long> getRealtionWorkFieldIdByModuleFieldIds(List<Long> moduleFieldIds) {
        if (null == moduleFieldIds || moduleFieldIds.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkFieldVal> wrapper = new QueryWrapper<>();
        wrapper.select("work_field_id");
        wrapper.in("module_field_id", moduleFieldIds);
        wrapper.last(" GROUP BY work_field_id");
        return this.list(wrapper).stream().map(ZjWorkFieldVal::getModuleFieldId).toList();
    }

    // 根据工单ID获取工单字段参数
    @Override
    public List<WorkDetailFieldParamVo> getOrderFieldParam(Long workId) {
        QueryWrapper<ZjWorkFieldVal> wrapper = new QueryWrapper<>();
        wrapper.select("id", "type", "name");
        wrapper.in("work_id", workId);
        List<ZjWorkFieldVal> fieldValList = this.list(wrapper);
        List<ZjWorkFieldValOption> optionList = workFieldValOptionService.getByWorkFieldValIds(fieldValList.stream().map(ZjWorkFieldVal::getId).toList());
        return fieldValList.stream().map(val -> {
            WorkDetailFieldParamVo vo = new WorkDetailFieldParamVo();
            BeanUtil.copyProperties(val, vo);
            vo.setVal(optionList.stream().filter(f -> Objects.equals(f.getWorkFieldValId(), val.getId())).map(ZjWorkFieldValOption::getOptValue).toList());
            return vo;
        }).toList();
    }

    // 根据工单字段ID & 工单列表搜索字段值获取工单ID
    @Override
    public List<Long> getWorkIdsByWorkFieldIdAndVal(Long fieldId, String fieldSearch) {
        if (null == fieldId || StringUtils.isBlank(fieldSearch)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkFieldVal> wrapper = new QueryWrapper<>();
        wrapper.select("work_id");
        wrapper.eq("work_field_id", fieldId);
//                .like("val", fieldSearch);
        List<ZjWorkFieldVal> fieldValList = this.list(wrapper);
        if (CollectionUtils.isEmpty(fieldValList)) {
            return new ArrayList<>();
        }
        return fieldValList.stream().map(ZjWorkFieldVal::getWorkId).distinct().toList();
    }

    // 根据模块ID获取工单列表显示的工单自定义字段
    @Override
    public List<ZjWorkFieldVal> getOrderListShowFieldByModuleIds(List<Long> moduleIds) {
        if (null == moduleIds || moduleIds.isEmpty()) {
            return new ArrayList<>();
        }
        List<ZjWorkModuleField> moduleFields = workModuleFieldService.getOrderListShowFieldByModuleIds(moduleIds);
        if (CollectionUtils.isEmpty(moduleFields)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkFieldVal> wrapper = new QueryWrapper<>();
        wrapper.select("id", "work_id", "work_field_id", "name");
        wrapper.in("work_field_id", moduleFields.stream().map(ZjWorkModuleField::getWorkFieldId).distinct().toList())
                .in("module_field_id", moduleFields.stream().map(ZjWorkModuleField::getId).distinct().toList())
                .in("type", FieldTypeConstant.FIELD_TYPE_1, FieldTypeConstant.FIELD_TYPE_3, FieldTypeConstant.FIELD_TYPE_4);
        return this.list(wrapper);
    }

    // 根据工单ID获取工单自定义字段导出数据
    @Override
    public List<WorkFieldValExtend> getOrderCustomFieldExportDataByWorkIds(List<Long> workIds) {
        if (CollectionUtil.isEmpty(workIds)) {
            return new ArrayList<>();
        }
        List<ZjWorkFieldVal> workFieldValList = workFieldValMapper.getOrderCustomFieldExportDataByWorkIds(workIds);
        if (CollectionUtil.isEmpty(workFieldValList)) {
            return new ArrayList<>();
        }
        List<ZjWorkFieldValOption> valOptions = workFieldValOptionService.getByWorkFieldValIds(workFieldValList.stream().map(ZjWorkFieldVal::getId).toList());
        return workFieldValList.stream().map(fieldVal -> {
            WorkFieldValExtend valExtend = new WorkFieldValExtend();
            BeanUtil.copyProperties(fieldVal, valExtend);
            valExtend.setValues(valOptions.stream().filter(f -> Objects.equals(f.getWorkFieldValId(), fieldVal.getId())).map(ZjWorkFieldValOption::getOptValue).toList());
            return valExtend;
        }).toList();
    }

    // 根据工单ID删除工单自定义字段
    @Override
    public void deleteByWorkId(Long workId) {
        workFieldValMapper.deleteByWorkId(workId);
    }
}
